import React, { useContext, useEffect, useState } from 'react';
import cs from 'classnames';

import styles from './style/index.module.less';
import {
  Button,
  Form,
  Grid,
  Link,
  Message,
  Space,
  Spin,
  Table,
  TableColumnProps,
  Upload,
} from '@arco-design/web-react';
import { IconDelete, IconPlus } from '@arco-design/web-react/icon';
import { GlobalContext } from '@/context';
import locale from './locale';
import useLocale from '@/utils/useLocale';
import AppUpload from '@/components/AppUpload';

const { Row, Col } = Grid;

export interface SignedDocHref {
  key?: number;
  href: string;
}

export function Signed({
  value,
  onPush,
}: {
  value: Array<SignedDocHref>;
  onPush: (signedDocHref: Array<SignedDocHref>) => void;
}) {
  const { rtl } = useContext(GlobalContext);
  const t = useLocale(locale);
  const columns: TableColumnProps[] = [
    {
      title: t['signed.id'],
      dataIndex: 'key',
    },
    {
      title: t['signed.signedAttachment'],
      dataIndex: 'href',
    },
    {
      title: t['signed.action'],
      dataIndex: 'action',
      render: (_, b) => (
        <Link hoverable={false} status="error" onClick={() => onRemove(b.key)}>
          {/* {t['delete']} */}
          <IconDelete />
        </Link>
      ),
    },
  ];
  const [signedDocHref, setSignedDocHref] =
    useState<Array<SignedDocHref>>(value);

  const onAdd = (e) => {
    const key =
      signedDocHref.length > 0
        ? signedDocHref[signedDocHref.length - 1].key + 1
        : 1;
    const files = e.map((a, k) => ({ href: a.href, key: key + k }));

    setSignedDocHref((a) => [...a, ...files]);
  };

  const onRemove = (key: number) => {
    setSignedDocHref(signedDocHref.filter((item) => item.key !== key));
  };

  useEffect(() => {
    onPush(signedDocHref);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [signedDocHref]);

  return (
    <div className={cs(styles['block'], rtl ? 'rtl' : '')}>
      <div className={styles['block-title']}>
        {t['signed.signed']}
        {/* <span className="red">*</span> */}
      </div>

      <Row gutter={24} align="end">
        <Col span={3}>
          <Space direction="vertical" size={[12, 18]}>
            <AppUpload
              onFile={onAdd}
              maxFileNum={10}
              fileNum={signedDocHref.length}
              tips={t['signed.signfile.tips']}
            >
              <Button
                type="primary"
                icon={<IconPlus />}
                disabled={signedDocHref.length >= 10}
              >
                {t['signed.add']}
              </Button>
            </AppUpload>
          </Space>
        </Col>
      </Row>
      <Table
        pagination={false}
        columns={columns}
        data={signedDocHref}
        border={{
          wrapper: true,
          cell: true,
        }}
      />
    </div>
  );
}

export default Signed;
